﻿
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var appModel = Windows.ApplicationModel;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var app = WinJS.Application;
    var utils = WinJS.Utilities;
    var searchPageURI = "/pages/search/searchResults.html";

    //resource variables
    var recentPostsTitle = WinJS.Resources.getString('recentPostsTitle').value;
    var categoryTitle = WinJS.Resources.getString('categoryTitle').value;
    var offlineTitle = WinJS.Resources.getString('offlineTitle').value;
    var aboutTitle = WinJS.Resources.getString('aboutTitle').value;
    var sharingErrorMessage = WinJS.Resources.getString('shareErrorMessage').value;

    var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();

    var ring;
    var main;

    var promise = null;
    var cache = app.sessionState;

    var _element;
    var _options;

    var _g;
    var _res;
    var that;
    var _viewState;
    var _lastSearch = "";
    //search
    appModel.Search.SearchPane.getForCurrentView().onquerysubmitted = function (args) {
        if (nav.location !== "/pages/search/searchResults.html") {
            //save nav history
            var saveHistory = removeSearchFromNavigationStack(nav.history);
            nav.navigate("/pages/search/searchResults.html", {
                queryText: args.detail[0].queryText,
                saveHistory: saveHistory
            });
            _options = args;
        } else {
            nav.history = removeSearchFromNavigationStack(nav.history);
            _lastSearch = args.queryText;
            _options = args;
            that._handleQuery(_element, args);
        }
        //searchPane.onQuerySubmitted = onQuerySubmitted();
    };

    ui.Pages.define(searchPageURI, {
        _filters: [],

        
        ready: function (element, options) {

            nav.history = removeSearchFromNavigationStack(nav.history);

            if (typeof nav.history.forwardStack[0] !== "undefined" && nav.history.forwardStack[0].location === "/pages/itemDetail/itemDetail.html") {
                nav.history.current.state.queryText = _lastSearch;
            }

            if (typeof options.saveHistory !== "undefined") {
                nav.history = removeSearchFromNavigationStack(options.saveHistory);
            }

            that = this;
            _element = element;

            if (_lastSearch !== "" || _viewState === appViewState.snapped) {
                _options = options;
            }

            var parent = element.querySelector('section');
            var pHeight = (parent.offsetHeight / 2) - parent.offsetTop;
            var ringContainer = element.querySelector('.progress-container');
            var rHeight = ringContainer.offsetHeight;
            var marginTop = pHeight + (rHeight / 2);
            ringContainer.style.marginTop = marginTop + "px";


            ring = element.querySelector(".progress-container");
            main = element.querySelector("section");
            var listView = element.querySelector("#zoomedInListView").winControl;
            listView.itemTemplate = element.querySelector(".itemtemplate");

            this._handleQuery(element, options);


            listView.element.focus();


        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
            if (promise != null) {
                promise.cancel();
            }
            that = null;
        },
        // This function updates the page layout in response to viewState changes.
        updateLayout: function (element, viewState, lastViewState) {
            
            _viewState = viewState;

            var result = element.querySelector("#snappContainer");
            result.innerHTML = '';

            toggleLoading(true);

            //var listView = element.querySelector(".resultslist").winControl;
            if (lastViewState !== viewState) {
                if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
                    var that = this;
                    if (typeof cache[_lastSearch] !== "undefined") {
                        //cache
                        _res = cache[_lastSearch];
                        that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
                    } else {
                        //load new data
                        promise = Data.searchPost(_lastSearch, null, false).then(function (res) {
                            _res = res;
                            if (res !== null || typeof res !== "undefined") {
                                cache[_lastSearch] = res;

                            }
                            that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
                        });

                    }
                }
            }
        },

        // This function filters the search data using the specified filter.
        _applyFilter: function (filter, originalResults) {
            if (filter.results === null) {
                filter.results = originalResults.createFiltered(filter.predicate);
            }
            return filter.results;
        },

        // This function responds to a user selecting a new filter. It updates the
        // selection list and the displayed results.
        _filterChanged: function (element, filterIndex) {
            var filterBar = element.querySelector(".filterbar");
            var listView = element.querySelector(".resultslist").winControl;

            utils.removeClass(filterBar.querySelector(".highlight"), "highlight");
            utils.addClass(filterBar.childNodes[filterIndex], "highlight");

            element.querySelector(".filterselect").selectedIndex = filterIndex;

            listView.itemDataSource = this._filters[filterIndex].results.dataSource;
        },

       
        // This function executes each step required to perform a search.
        _handleQuery: function (element, args) {
            var originalResults;
            _lastSearch = args.queryText;
            if (promise != null) {
                promise.cancel();
            }

            toggleLoading(true);
            document.querySelector('.resultsmessage').style.display = "none";

            document.querySelector(".pagetitle").textContent = "Suche nach “" + _lastSearch + '”';

            var that = this;
            if (typeof cache[_lastSearch] !== "undefined") {
                //cache
                _res = cache[_lastSearch];
                that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
            } else {
                //load new data
                promise = Data.searchPost(_lastSearch, null, false).then(function (res) {
                    _res = res;
                    if (res !== null || typeof res !== "undefined") {
                        cache[_lastSearch] = res;

                    }
                    that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
                });

            }
        },

        // This function updates the ListView with new layouts
        _initializeLayout: function (viewState, element) {
            if (promise != null) {
                promise.cancel();
            }
            document.querySelector('.resultsmessage').style.display = "none";
            if (viewState === appViewState.snapped) {

                promise = Data.searchPostList(_res).then(function (e) {

                    toggleLoading(false, true);

                    var isEmpty = true;

                    var x = [];
                    for (var i in e) {
                        if (e[i].length > 0) {
                            isEmpty = false;
                        }
                    }

                    if (typeof e == "undefined" || isEmpty || e == null) {
                        document.querySelector('.resultsmessage').style.display = "block";
                    } else {
                        document.querySelector('.resultsmessage').style.display = "none";
                    }

                    if (typeof e != "undefined" && isEmpty == false && e !== null) {
                        //var resultList = [];

                        var x = [];
                        for (var i in e) {
                            var y = {
                                key: i,
                                posts: e[i]
                            };
                            x.push(y);
                        }
                        var sorted = x.sort(function (a, b) {
                            // Sort by the key value in each array
                            var A = a.key.toLowerCase();
                            var B = b.key.toLowerCase();
                            if (A < B) {
                                return -1;
                            } else if (A > B) {
                                return 1;
                            } else {
                                return 0;
                            }
                        });
                        for (var i = 0; i < sorted.length; i++) {

                            if (sorted[i].posts.length > 0) {
                                //resultList.push(header);
                                var key = sorted[i].key;

                                var result = element.querySelector("#snappContainer");
                                //create list
                                var myList = new WinJS.Binding.List(sorted[i].posts);

                                var groupTitle = document.createElement("div");
                                groupTitle.className = "SearchListgroupTitle";

                                groupTitle.innerHTML = key + " (" + e[key].length + ")";

                                var body = document.createElement("div");
                                var h = 103 * sorted[i].posts.length;
                                body.style.height = h + "px";
                                body.className = "snapSearchList searchList" + key;

                                var container = document.createElement("div");
                                container.className = "searchListContainer";
                                container.style.height = 56 + h + "px";

                                var nestedListView = document.createElement("div");
                                var listView = new WinJS.UI.ListView(nestedListView);
                                listView.layout = new WinJS.UI.ListLayout();
                                listView.itemDataSource = myList.dataSource;
                                listView.itemTemplate = itemTemplateFunctionSnapped;
                                listView.key = key;
                                listView.selectionMode = "none";

                                WinJS.UI.setOptions(listView, {
                                    itemDataSource: myList.dataSource,
                                    itemTemplate: itemTemplateFunctionSnapped,
                                    layout: new WinJS.UI.ListLayout()
                                });

                                body.appendChild(nestedListView);
                                container.appendChild(groupTitle);
                                container.appendChild(body);
                                result.appendChild(container);

                            }

                        }

                    } else {
                        document.querySelector('.resultsmessage').style.display = "block";
                    }
                });


            } else {

                var params = Data.getGroupedSearch(_res);
                _g = params.list;

                toggleLoading(false, false);

                if (params.empty === true) {
                    document.querySelector('.resultsmessage').style.display = "block";
                } else {
                    document.querySelector('.resultsmessage').style.display = "none";
                }

                var listView = element.querySelector("#zoomedInListView").winControl;
                listView.selectionMode = 'none';

                listView.oniteminvoked = itemInvoked;

                var gridLayoutOptions = {
                    groupHeaderPosition: 'top',
                    groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                };

                WinJS.UI.setOptions(listView, {
                    itemDataSource: _g.dataSource,
                    groupDataSource: _g.groups.dataSource,
                    itemTemplate: itemTemplateFunction,
                    groupHeaderTemplate: groupHeaderTemplateFunction,
                    layout: new WinJS.UI.GridLayout(gridLayoutOptions)
                });

            }
        },

        _itemInvoked: function (args) {
            var invokedItem = g.getAt(e.detail.itemIndex);
            WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });
            //args.detail.itemPromise.done(function itemInvoked(item) {
            //    // TODO: Navigate to the item that was invoked.
            //});
        },


    });

    function headerCallback(e) {

        var headerTitle = e.firstElementChild.textContent;
        
        Data.getCategoryByTitle(headerTitle).then(function (parameters) {
            WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                from: 'categoryItem',
                item: parameters
            });
        });
    }

    function itemInvoked(e) {
        //log("invoked" + g.getAt(e.detail.itemIndex).key);
        var invokedItem = _g.getAt(e.detail.itemIndex);
        WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });

    }
    //Template Functions
    function itemTemplateFunctionSnapped(itemPromise) {
        return itemPromise.then(function (item) {

            var itemTemplate = _element.querySelector('#snapItem');

            if (item.data.isHeader == true) {
                itemTemplate = _element.querySelector('#snapHeader');
            } else {
                if (typeof item.data.teaserImage !== "undefined") {
                    itemTemplate = _element.querySelector('#snapItem-image');
                } else {
                    itemTemplate = _element.querySelector('#snapItem');
                }
            }

            // Render selected template to DIV container
            var container = document.createElement("div");
            container.item = item;
            container.addEventListener("click", function (e) {
                var invokedItem = container.item.data;
                WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });
            }, false);
            itemTemplate.winControl.render(item.data, container);

            return container;
        });
    }

    function itemTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {

            // Select template
            var itemTemplate;
            if (typeof item.data.teaserImage !== "undefined") {
                itemTemplate = _element.querySelector('#itemTemplate-Image');
            } else {
                itemTemplate = _element.querySelector('#itemTemplate-RecentPost');
            }

            // Render selected template to DIV container
            var container = document.createElement("div");
            itemTemplate.winControl.render(item.data, container);

            return container;
        });
    }

    function groupHeaderTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {
            var groupHeaderTemplate = _element.querySelector('#groupHeaderTemplate');
            // Render selected template to DIV container
            item.data.titleWithSize = trimString(Helper.htmlSpecialChars(item.data.titleReal,true),17) + " (" + item.groupSize + ")";
            var container = document.createElement("div");
            groupHeaderTemplate.winControl.render(item.data, container);
            return container;
        });
    }
    function trimString(string, size) {
        
        if (typeof string !== "undefined") {
            if (string.length > size) {
                var trimedString = string.substring(0, size - 3);
                trimedString += '...';
                return trimedString;
            }
            return string;
        } else {
            return "";
        }
    }

    function toggleLoading(isLoading, isSnapped, fail) {
        if (isLoading) {
            _element.querySelector(".progress-container").style.display = "block";
            _element.querySelector('#snappContainer').style.display = "none";;
            _element.querySelector('#fullContainer').style.display = "none";;
        }
        else {
            _element.querySelector(".progress-container").style.display = "none";
            if (isSnapped) {
                _element.querySelector('#snappContainer').style.display = "block";;
                _element.querySelector('#fullContainer').style.display = "none";;
            }
            else {
                _element.querySelector('#snappContainer').style.display = "none";;
                _element.querySelector('#fullContainer').style.display = "block";;
            }
        }
    }

    function removeSearchFromNavigationStack(history) {
        for (var i = 0; i < history.backStack.length; i++) {
            if (history.backStack[i].location == "/pages/search/searchResults.html") {
                history.backStack.splice(i, 1);
            }
        }
        return history;
    }
    WinJS.Namespace.define('SearchFunctions', {
        headerCallback: headerCallback
    });
})();
